import { config } from '../config.js'
const app = getApp()

class HTTP {

  show_error(error_msg) {

  }

  request({ url, data = {}, method = 'GET' }) {
    return new Promise((resolve, reject) => {
      this._request(url, resolve, reject, data, method)
    }).catch(function (reason) {
      console.log('catch:', reason);
      // throw(reason)
    })
  }

  //http 请求类, 当noRefech为true时，不做未授权重试机制
  _request(url, resolve, reject, data = {}, method = 'GET') {
    var that = this
    var url = config.api_php_url + url;

    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'content-type': 'application/json',
        'token': app.getGlobalToken()
      },
      success: function (res) {
        // console.log(res)
        // 判断以2（2xx)开头的状态码为正确， 4xx还是在success 中处理
        // 异常不要返回到回调中，就在request中处理，记录日志并showToast一个统一的错误即可
        const code = res.data.code; // let code = res.statusCode.toString()  if(code.startWith('2'))
        if (code === 1) {
          resolve(res.data);
        } else {
          reject(res.data.message)
          console.log(url, res.data.message)
          // wx.showToast({
          //   title: res.data.message,
          //   icon: 'none',
          //   duration: 3000
          // })
        }
      },
      fail: function (err) {
        reject()
        wx.showToast({
          title: '网络异常，请检查您的网络状态!',
          icon: 'none',
          duration: 2000
        })
      }
    })

  }



}

export { HTTP };